<template>
	<div class="store-type-tree">
		<el-card shadow="hover" :body-style="{ padding: '10px' }">
			<template #header>
				<div class="card-header">
					<span>物资分类</span>
					<el-button text size="small" @click="refreshTree">
						<el-icon><Refresh /></el-icon>
					</el-button>
				</div>
			</template>
			<el-tree
				ref="treeRef"
				:data="state.treeData"
				:props="{ children: 'children', label: 'label', value: 'value' }"
				node-key="value"
				:expand-on-click-node="false"
				:highlight-current="true"
				:default-expand-all="false"
				:default-expanded-keys="[0]"
				@node-click="handleNodeClick"
				v-loading="state.loading"
				class="store-type-tree-container"
			>
				<template #default="{ node, data }">
					<div class="tree-node">
						<el-icon v-if="data.children && data.children.length > 0" class="folder-icon">
							<Folder />
						</el-icon>
						<el-icon v-else class="document-icon">
							<Document />
						</el-icon>
						<span class="node-label">{{ node.label }}</span>
						<span class="node-count" v-if="data.materialCount !== undefined">({{ data.materialCount }})</span>
					</div>
				</template>
			</el-tree>
		</el-card>
	</div>
</template>

<script lang="ts" setup name="storeTypeTree">
import { ref, reactive, onMounted, nextTick, watch } from 'vue';
import { Refresh, Folder, Document } from '@element-plus/icons-vue';

interface StoreTypeNode {
	id: string | number;
	name: string;
	pid?: string | number | null;
	children?: StoreTypeNode[];
	materialCount?: number;
	value?: string | number; // API 返回的字段
	label?: string; // API 返回的字段
}

// Props
const props = defineProps<{
	data?: StoreTypeNode[];
}>();

// Emits
const emit = defineEmits<{
	nodeClick: [node: StoreTypeNode, treeNode: any];
	refresh: [];
}>();

const treeRef = ref();
const state = reactive({
	loading: false,
	treeData: [] as StoreTypeNode[],
	currentNodeId: null as number | null,
});

// 设置树数据
const setTreeData = (data: StoreTypeNode[]) => {
	// 添加"全部"根节点
	const allNode: StoreTypeNode = {
		id: 0,
		value: 0,
		name: '全部物资分类',
		label: '全部物资分类',
		children: data || [],
	};
	state.treeData = [allNode];
};

// 刷新树
const refreshTree = () => {
	emit('refresh');
};

// 节点点击事件
const handleNodeClick = (data: StoreTypeNode, node: any) => {
	const nodeId = data.id || data.value; // 兼容不同的字段名
	state.currentNodeId = nodeId as number;
	emit('nodeClick', data, node);
};

// 设置当前选中节点
const setCurrentKey = (key: number | null) => {
	nextTick(() => {
		if (treeRef.value) {
			treeRef.value.setCurrentKey(key);
			state.currentNodeId = key;
		}
	});
};

// 展开所有节点
const expandAll = () => {
	nextTick(() => {
		if (treeRef.value) {
			const nodes = treeRef.value.store._getAllNodes();
			nodes.forEach((node: any) => {
				node.expanded = true;
			});
		}
	});
};

// 收起所有节点
const collapseAll = () => {
	nextTick(() => {
		if (treeRef.value) {
			const nodes = treeRef.value.store._getAllNodes();
			nodes.forEach((node: any) => {
				node.expanded = false;
			});
		}
	});
};

// 监听props变化
watch(
	() => props.data,
	(newData) => {
		console.log('树组件接收到数据:', newData); // 调试信息
		if (newData) {
			setTreeData(newData);
		}
	},
	{ immediate: true }
);

// 挂载时设置默认选中
onMounted(() => {
	nextTick(() => {
		setCurrentKey(0); // 默认选中"全部"
	});
});

// 暴露方法给父组件
defineExpose({
	setCurrentKey,
	expandAll,
	collapseAll,
	refreshTree,
});
</script>

<style scoped>
.store-type-tree {
	height: 100%;
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.store-type-tree-container {
	height: calc(100vh - 200px);
	overflow-y: auto;
}

.tree-node {
	display: flex;
	align-items: center;
	width: 100%;
}

.folder-icon,
.document-icon {
	margin-right: 6px;
	font-size: 14px;
}

.folder-icon {
	color: #e6a23c;
}

.document-icon {
	color: #909399;
}

.node-label {
	flex: 1;
	font-size: 14px;
}

.node-count {
	color: #909399;
	font-size: 12px;
	margin-left: 4px;
}

.el-tree {
	background-color: transparent;
}

:deep(.el-tree-node__content) {
	height: 32px;
}

:deep(.el-tree-node__content:hover) {
	background-color: var(--el-tree-node-hover-bg-color);
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
	background-color: var(--el-color-primary-light-9);
	color: var(--el-color-primary);
}
</style>